import mongoose from 'mongoose';
import { IUser } from '../models/user';
import { User } from '../models/user';

/**
 * 组织数据访问对象
 * 处理组织相关的数据库操作
 */
export class OrganizationDAO {

  /**
   * 获取组织下的用户
   * @param organizationQuery 组织查询条件
   * @returns 用户列表
   */
  async getOrganizationUsers(organizationQuery: {
    teamId?: mongoose.Types.ObjectId;
    departmentId?: mongoose.Types.ObjectId;
    groupId?: mongoose.Types.ObjectId;
  }): Promise<IUser[]> {
    try {
      const query: any = {};
      
      if (organizationQuery.teamId) {
        query.teamId = organizationQuery.teamId;
      }
      
      if (organizationQuery.departmentId) {
        query.departmentId = organizationQuery.departmentId;
      }
      
      if (organizationQuery.groupId) {
        query.groupId = organizationQuery.groupId;
      }
      
      return await User.find(query).exec();
    } catch (error) {
      throw new Error(`获取组织用户失败: ${error}`);
    }
  }
  
  /**
   * 获取用户的组织信息
   * @param userId 用户ID
   * @returns 组织信息
   */
  async getUserOrganization(userId: mongoose.Types.ObjectId): Promise<any> {
    try {
      const user = await User.findById(userId)
        .populate('teamId')
        .populate('departmentId')
        .populate('groupId')
        .exec();
      
      if (!user) {
        throw new Error('用户不存在');
      }
      
      return {
        team: user.teamId,
        department: user.departmentId,
        group: user.groupId
      };
    } catch (error) {
      throw new Error(`获取用户组织信息失败: ${error}`);
    }
  }
  
  /**
   * 更新用户组织信息
   * @param userId 用户ID
   * @param organizationData 组织数据
   * @returns 更新后的用户
   */
  async updateUserOrganization(userId: mongoose.Types.ObjectId, organizationData: {
    teamId?: mongoose.Types.ObjectId;
    departmentId?: mongoose.Types.ObjectId;
    groupId?: mongoose.Types.ObjectId;
  }): Promise<IUser | null> {
    try {
      return await User.findByIdAndUpdate(
        userId,
        organizationData,
        { new: true }
      ).exec();
    } catch (error) {
      throw new Error(`更新用户组织信息失败: ${error}`);
    }
  }
}

export default OrganizationDAO;